Skip to Content

功能

  • 执行特定方法,并通过比较预期值和实际值来验证该方法的正确性

实现

  1. 启动测试环境的Spring应用上下文:通过 @SpringBootTest 注解可以启动Spring上下文,执行Web环境或服务层的集成测试
  2. 将需要测试的类注入测试类中:通过 @Autowired 注解注入需要测试的对象
  3. 定义测试方法:通过 @Test 注解标记测试方法,并进行预期判断
  4. 定义测试前后的初始化和清理工作:通过@BeforeAll@AfterAll 注解在所有测试方法执行之前和之后分别执行一次特定方法
@SpringBootTest class studentApplicationTests { @Autowired public StudentMapper studentMapper; @BeforeAll public static void setup() { // 在所有测试方法执行之前执行的代码 System.out.println("Before All Tests"); } @AfterAll public static void tearDown() { // 在所有测试方法执行之后执行的代码 System.out.println("After All Tests"); } @Test public void getGirl() { List<Student> students = studentMapper.findGirl(); for (Student student : students) { System.out.println(student); } } @Test public void insertStudent() { Student student = new Student(); student.setName("FL"); student.setGender('男'); student.setAge(20); student.setClassName("计算机"); if (studentMapper.insertStudent(student) > 0) { System.out.println("插入成功"); }else { System.out.println("插入失败"); } } }
Last updated on